package com.agent.interceptor;

import com.agent.utils.JWTUtils;
import com.agent.utils.UserContext;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/*
    JWT 认证拦截器
 */

@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    // 拦截器处理逻辑
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("开始JWT令牌校验.........");
        String path = request.getRequestURI();
        // Exclusions are configured in WebMvcConfig; here we just enforce for other paths
        // 获取请求中的授权头
        String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"Unauthorized: Missing Bearer token\"}");
            return false;
        }
        // 得到jwt令牌
        String token = authHeader.substring(7);
        try {
            // 解析令牌
            Jws<Claims> jws = JWTUtils.parse(token);
            Long userId = jws.getBody().get("uid", Long.class);
            System.out.println("用户ID：" + userId);
            // 非空判断
            if (userId == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"code\":401,\"msg\":\"Unauthorized: Invalid token payload\"}");
                return false;
            }
//            request.setAttribute("userId", userId);
            // 存储用户ID
            UserContext.setUserId(userId);
            request.setAttribute("userId", userId);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"Unauthorized: Token invalid or expired\"}");
            return false;
        }
    }

    // 拦截器处理完成
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal，防止内存泄漏
        UserContext.clear();
    }
}
